import {
  selectIcCardList,
  selectIcCardDetail,
  saveIcCard,
  getIcCardCookie,
  getRandom,
  cookiesRefresh,
} from '@/services/iccard';
import prompt from '@/components/Prompt';

export default {
  namespace: 'iccard',

  state: {
    icCardList: {}, // 帐单列表
    icCardDetail: {},
  },

  effects: {
    /**
     * 查询列表
     */
    *selectIcCardList({ payload, callback }, { call, put }) {
      const response = yield call(selectIcCardList, payload);
      const { code, data } = response;
      if (code !== 0) return;
      const { list, pageSize, total, pageNum } = data;
      yield put({
        type: 'saveAllValus',
        payload: {
          icCardList: {
            pagination: {
              current: pageNum,
              pageSize,
              total,
            },
            list,
          },
        },
      });
      callback && callback(list);
    },
    /**
     * 查询详情---
     */
    *selectIcCardDetail({ payload, callback }, { call, put }) {
      const response = yield call(selectIcCardDetail, payload);
      const { code, data } = response;
      if (code !== 0) return;
      yield put({
        type: 'saveDetail',
        payload: { icCardDetail: { [payload.id]: data } },
      });
      callback && callback(data);
    },
    *saveIcCard({ payload, callback }, { call }) {
      const response = yield call(saveIcCard, payload);
      const { code, data, message } = response;
      const content = `${payload.id ? '编辑' : '新增'}${message}`;
      if (code !== 0) return;
      prompt({ content });
      callback && callback(data);
    },
    *getIcCardCookie({ payload, callback }, { call }) {
      const response = yield call(getIcCardCookie, payload);
      console.log('response');
      callback && callback(data);
    },

    *getRandom({ payload, callback }, { call }) {
      const response = yield call(getRandom, payload);
      const { code, data, message } = response;
      if (code === 0) {
        callback && callback(data);
      }
    },
    *cookiesRefresh({ payload, callback }, { call }) {
      const response = yield call(cookiesRefresh, payload);
      const { code, data, message } = response;
      if (code === 0) {
        callback && callback(data);
      }
    },

    /**
     * 设置表单参数
     */
    *allValus({ payload }, { _, put }) {
      yield put({
        type: 'saveAllValus',
        payload,
      });
    },
  },

  reducers: {
    //设置表单参数
    saveAllValus(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
    saveDetail(state, { payload }) {
      return {
        ...state,
        icCardDetail: { ...state.icCardDetail, ...payload.icCardDetail },
      };
    },
  },
};
